<% layout('/layouts/_default.html', {title: '角色管理', libs: ['validate', 'zTree']}){ %>
<%
var items=[];
%>
<div class="main-content">
  <div class="box box-main">
    <div class="box-header">
      <div class="box-title">
        <i class="fa icon-people"></i> ${op=='add' ? '新增角色' : op == 'auth' ? '角色授权功能菜单' : '编辑角色'}
      </div>
      <div class="box-tools pull-right">
        <button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button>
      </div>
    </div>
    <#form:form id="inputForm" model="${role}" action="${ctxPath}/role/save" method="post" class="form-horizontal">
      <#form:hidden name="op" value="${op}"/>
      <div class="box-body">
        <div class="form-unit">基本信息</div>
        <div class="row">
          <div class="col-xs-6">
            <div class="form-group">
              <label class="control-label col-sm-4" title="">
                <span class="required ">*</span> 角色名称：<i class="fa icon-question hide"></i></label>
              <div class="col-sm-8">
                <#form:hidden path="oldRoleName" />
                <#form:input path="roleName" maxlength="100" class="form-control required " />
              </div>
            </div>
          </div>
          <div class="col-xs-6">
            <div class="form-group">
              <label class="control-label col-sm-4" title="">
                <span class="required ">*</span> 角色编码：<i class="fa icon-question hide"></i></label>
              <div class="col-sm-8">
                <#form:input path="roleCode" maxlength="64" readonly="${op!='add'}"  class="form-control required abc"/>
              </div>
            </div>
          </div>
        </div>
        <% if(op == 'add' || op == 'edit') {%>
        <div class="row">
          <div class="col-xs-12">
            <div class="form-group">
              <label class="control-label col-sm-2" title="">
                <span class="required hide">*</span> 备注信息：<i class="fa icon-question hide"></i></label>
              <div class="col-sm-10">
                <#form:textarea path="remarks" rows="4" maxlength="500" class="form-control "/>
              </div>
            </div>
          </div>
        </div>
        <% } %>
        <div class="form-unit">授权功能菜单</div>
        <div id="menuTrees"></div>
        <script id="menuTpl" type="text/template">
          <div class="pull-left" style="padding:0 15px;min-width:300px;">
            <div class="box box-solid" style="background:#FAFAFA">
              <div class="box-header">
                <div class="box-title icheck">
                  <label><input type="checkbox" id="checkall_{{d.key}}"
                    class="checkall"/> {{d.label}}</label>
                </div>
                <div class="box-tools pull-right" style="top:8px;">
                  <a class="btn btn-box-tool" id="expand_{{d.key}}"
                    value="menuTree_{{d.key}}" >展开</a>/<a
                    class="btn btn-box-tool" id="collapse_{{d.key}}"
                    value="menuTree_{{d.key}}" >折叠</a>
                </div>
              </div>
              <div class="box-body">
                <div id="menuTree_{{d.key}}" class="ztree"></div>
              </div>
            </div>
          </div>
        </script>
        <#form:hidden id="roleMenuListJson" path="roleMenuListJson" />
      </div>
      <div class="box-footer">
        <div class="row">
          <div class="col-sm-offset-2 col-sm-10">
            <button type="submit" class="btn btn-sm btn-primary" id="btnSubmit"><i class="fa fa-check"></i> 保 存</button>&nbsp;
            <button type="button" class="btn btn-sm btn-default" id="btnCancel" onclick="js.closeCurrentTabPage()"><i class="fa fa-reply-all"></i> 关 闭</button>
          </div>
        </div>
      </div>
    </#form:form>
  </div>
</div>
<% } %>
<script>
$("#inputForm").validate({
  submitHandler: function(form){
    // 获取数据权限数据
    var menuData = [];
    $.each(menuTrees, function(key, menuTree){
      var treeNodes = menuTree.getCheckedNodes(true);
      for(var i=0; i<treeNodes.length; i++) {
        menuData.push(treeNodes[i].id);
      }
    });
    $("#roleMenuListJson").val(JSON.stringify(menuData));
    // 提交表单数据
    js.ajaxSubmitForm($(form), function(data){
      js.showMessage(data.message);
      if(data.result == Global.TRUE){
        js.closeCurrentTabPage(function(contentWindow){
          contentWindow.page();
        });
      }
    }, "json");
    }
});
//加载数据权限树结构
var setting = {
  check:{enable:true,nocheckInherit:true,chkboxType:{"Y":"ps","N":"ps"}},
  view:{selectedMulti:false,nameIsHTML: true},
  data:{simpleData:{enable:true},key:{title:"title"}},
  callback:{
    beforeClick: function (treeId, treeNode, clickFlag) {
      var tree = $.fn.zTree.getZTreeObj(treeId);
      tree.checkNode(treeNode, !treeNode.checked, true, true);
      return false;
    },
    onCheck: function (event, treeId, treeNode){
      var tid = treeNode.tId;
      if(!treeNode.checked){
        $(".checkall[value="+treeId+"]").each(function(){
          if(this.checked){
              $(this).removeAttr("checked").iCheck('update');
          }
          return false;
        }); 
      }
    }
  }
},
sysCodeDict = ${@DictUtil.getDictListJson("sys_codes")},
menuTrees = {}; // 用sysCode分类存储所有菜单树
$.ajax({
  type: 'POST',
  url: "${ctxPath}/role/menuTreeData?___t=" + new Date().getTime(),
  data: {roleCode: '${role.roleCode}'},
  dataType: 'json',
  async: false,
  error: function(data){
    js.showErrorMessage(data.responseText);
  },
  success: function(data, status, xhr){
    for (var sysCode in data.menuMap){
      var menuMap = data.menuMap[sysCode];
      $('#menuTrees').append(js.template('menuTpl', {key: sysCode, 
        label: js.getDictLabel(sysCodeDict, sysCode, '未知', true)}));
      // 初始化树结构
      var tree = $.fn.zTree.init($("#menuTree_"+sysCode), setting, menuMap);
      // 展开第一级节点
      var nodes = tree.getNodesByParam("level", 0);
      for(var i=0; i<nodes.length; i++) {
        tree.expandNode(nodes[i], true, false, false);
      }
      // 展开第二级节点
      nodes = tree.getNodesByParam("level", 1);
      for(var i=0; i<nodes.length; i++) {
        tree.expandNode(nodes[i], true, false, false);
      }
      // 默认展开全部节点
      //tree.expandAll(true);
      // 树结构：全选、取消全选
      $('#checkall_'+sysCode).iCheck({
            checkboxClass:'icheckbox_minimal-grey'
        }).on('ifChecked ifUnchecked', function(){
        var sysCode = $(this).attr('sysCode');
        if(this.checked){
          menuTrees[sysCode].checkAllNodes(true);
        }else{
          menuTrees[sysCode].checkAllNodes(false);
        }
      }).attr("sysCode", sysCode);
      // 展开和折叠按钮绑定
      $('#expand_'+sysCode).click(function(){
        var sysCode = $(this).attr('sysCode');
        menuTrees[sysCode].expandAll(true);
      }).attr("sysCode", sysCode);
      $('#collapse_'+sysCode).click(function(){
        var sysCode = $(this).attr('sysCode');
        menuTrees[sysCode].expandAll(false);
      }).attr("sysCode", sysCode);
      // 将树对象存储到全局数组里
      menuTrees[sysCode] = tree;
    }
    // 默认选择节点 
    for (var idx in data.roleMenuList){
      var roleMenu = data.roleMenuList[idx], sysCode = roleMenu.sysCode;
      var node = menuTrees[sysCode].getNodeByParam("id",roleMenu.menuCode);
      try{menuTrees[sysCode].checkNode(node, true, false);}catch(e){}
    }
  }
});
</script>
